package com.freight.user.serviceimpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.redis.RedisTemplateHelper;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.OperationLogService;
import com.freight.core.service.UserService;
import com.freight.file.constants.FileConstant;
import com.freight.file.entity.File;
import com.freight.file.service.FileService;
import com.freight.file.util.FileUtils;
import com.freight.file.util.MyFileUtils;
import com.freight.file.util.VehicleOcrUtil;
import com.freight.file.vo.PicFileVo;
import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import com.freight.msg.utils.MyJPushClient;
import com.freight.user.dao.VehicleLicenseDao;
import com.freight.user.dto.VehicleDetailInfoDto;
import com.freight.user.dto.VehicleLicenseDto;
import com.freight.user.entity.*;
import com.freight.user.mapper.*;
import com.freight.user.service.DriverUserService;
import com.freight.user.service.VehicleLicenseService;
import com.freight.user.util.GpsUtil;
import com.freight.user.util.UserDtoUtils;
import com.freight.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 驾驶证接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class VehicleLicenseServiceImpl implements VehicleLicenseService {

    @Autowired
    private VehicleLicenseDao vehicleLicenseDao;

    @Autowired
    private DriverVoMapper driverVoMapper;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    DriverUserService driverUserService;

    @Autowired
    private VehicleVoMapper vehicleVoMapper;

    @Autowired
    FileService fileService;

    @Autowired
    UserService userService;

    @Autowired
    private RedisTemplateHelper redisTemplate;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private OperationLogService operationLogService;

    private GpsUtil gpsUtil = new GpsUtil();

    @Override
    public VehicleLicenseDao getRepository() {
        return vehicleLicenseDao;
    }


    @Override
    public VehicleGpalInfoVo getVehicleGpalInfoVo(String gpsEquipment) {

        VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(gpsEquipment);

        Double goodWeight = vehicleVoMapper.getVehicleGpalOrder(vehicleGpalInfoVo.getVehicleId());

        if(goodWeight!=null && goodWeight>0){
            vehicleGpalInfoVo.setGoodWeight(goodWeight);
            vehicleGpalInfoVo.setTaskState("1");
        }

        return vehicleGpalInfoVo;
    }

    @Override
    public List<HistoryVehicleVo> historyVehicle(String vehicleNum) {

        return vehicleVoMapper.historyVehicle(vehicleNum);
    }

    @Override
    public JSONObject vehicleposition(String vehicleId) {
        JSONObject returnJson = new JSONObject();
        String gpsEquipment = vehicleId;
        if(vehicleId.length()<6){
            VehicleLicense vehicleLicense = vehicleLicenseDao.getOne(Long.valueOf(vehicleId));
            if(vehicleLicense.getGpsEquipment()==null || vehicleLicense.getGpsEquipment().equals("")){
                throw new FreightException("请先设置车辆GPS设备号");
            }
            returnJson.put("vehicleNum",vehicleLicense.getVehicleNum());
            returnJson.put("gpsEquipment",vehicleLicense.getGpsEquipment());
            gpsEquipment = vehicleLicense.getGpsEquipment();
        }

        List vehicleList = new ArrayList();
        vehicleList.add(gpsEquipment);

        JSONObject data = new JSONObject();
        data.put("deviceids",vehicleList);
        data.put("lastquerypositiontime",0);
        JSONObject requestJson = gpsUtil.gpsPost(data,"action=lastposition&",redisTemplate);
        if(requestJson!=null && requestJson.getInteger("status")==0){
            JSONArray jsonArray = requestJson.getJSONArray("records");
            if(jsonArray!=null&&jsonArray.size()>0){
                JSONObject json = jsonArray.getJSONObject(0);
                returnJson.put("lat",json.getDouble("callat"));
                returnJson.put("lon",json.getDouble("callon"));
                returnJson.put("devicetime",json.getDouble("devicetime"));
                returnJson.put("speed",json.getDouble("speed")/1000);
            }else {
                throw new FreightException("GPS设备异常");
            }
        }else {
            throw new FreightException("GPS设备异常");
        }
        return requestJson;
    }

    @Override
    public PlaterVehicleLicenseVo getPcDriverLicenseId(Long vehicleId) {

        PlaterVehicleLicenseVo platerVehicleLicenseVo=vehicleVoMapper.getPcDriverLicenseId(vehicleId);


        return platerVehicleLicenseVo;
    }

    public VehiceInfoVo getDriverLicenseId(Long vehicleId){

        VehiceInfoVo vehiceInfoVo = new VehiceInfoVo();
        VehicleLicense vehicleLicense=get(vehicleId);
        User u = userService.get(vehicleLicense.getManageUserId());
        ObjectUtil.copyPropertiesIgnoreNull(vehicleLicense,vehiceInfoVo);
        vehiceInfoVo.setNickName(u.getNickName());
        return vehiceInfoVo;

    }

    @Override
    public void saveVehicleLicenseInfo(VehicleLicenseDto vehicleLicenseDto) {
        User u = securityUtil.getCurrUser();
        Long userId = vehicleLicenseDto.getUserId();
        String logContent = "";
        if(userId == null){
            userId = u.getId();
        }
        DriverUser driverUser = driverVoMapper.getDriverVoUserId(userId);

        Long vehicleId = vehicleLicenseDto.getVehicleId();
        VehicleLicense vehicleLicense =new VehicleLicense();
        // 上传过
        if (vehicleId != null && vehicleId > 0) {
            vehicleLicense = vehicleLicenseDao.getOne(vehicleId);
            if((vehicleLicense.getRegistStatus() == 1 || vehicleLicense.getRegistStatus() == 2
                    || vehicleLicense.getRegistStatus() == 3) && !vehicleLicense.getVehicleNum().equals(vehicleLicenseDto.getVehicleNum())){
                throw new FreightException("不能更换车辆");
            }
            ObjectUtil.copyPropertiesIgnoreNull(vehicleLicenseDto, vehicleLicense);
            logContent = "修改车辆信息";
        } else {
            List<VehicleLicense> v=vehicleVoMapper.getVehicleInfoByUservin(vehicleLicenseDto.getVehicleNum());

            if(v!=null&&v.size()>0){
                throw new FreightException("车辆已存在");
            }
            ObjectUtil.copyPropertiesIgnoreNull(vehicleLicenseDto, vehicleLicense);
            logContent = "上传车辆信息";
        }

        if(u.getUserType() == 2 && vehicleLicense.getRegistStatus() == 1){
            vehicleLicense.setRegistStatus(CommonConstant.REGISTED);//状态改为 1
        }else {
            vehicleLicense.setRegistStatus(CommonConstant.REGISTING);//状态改为 2 审核中
        }

        vehicleLicense.setManageUserId(userId);
        vehicleLicense = vehicleLicenseDao.save(vehicleLicense);
        driverUser.setVehicleId(vehicleLicense.getId());
        driverUserService.save(driverUser);
        //操作记录
        operationLogService.saveOperationLog(4,logContent,vehicleLicense.getId().toString());

    }

    @Override
    public PicFileVo uploadVehiclePic(MultipartFile file, String fileType) {
        User u = securityUtil.getCurrUser();
        java.io.File picFile = null;
        try {
            picFile = MyFileUtils.convert(file);
        } catch (IOException e) {
            throw new FreightException("解析行驶证文件异常");
        }
        PicFileVo res = new PicFileVo();
        File sfile = fileService.saveFileByUserId(file, fileType);
        res.setFileId(sfile.getId());

        String image_64 = FileUtils.baiud_img_file(picFile);
        picFile.delete();
        switch (fileType) {
            case FileConstant.VEHICLE_BACK_PIC: {

                //百度
                res = VehicleOcrUtil.baiDuBackVehicle(image_64,redisTemplate);
                if(res==null){
                    throw new FreightException("图片不清晰： 请重新上传图片");
                }
                res.setFileId(sfile.getId());
                res.setFilepath(sfile.getUrl());
                break;
            }
            case FileConstant.VEHICLE_FONT_PIC: {

                //百度
                res = VehicleOcrUtil.baiDuJustVehicle(image_64,redisTemplate);
                if(res==null){
                    throw new FreightException("图片不清晰： 请重新上传图片");
                }
                res.setFileId(sfile.getId());
                res.setFilepath(sfile.getUrl());
                break;
            }

            default:
                throw new FreightException("文件格式异常");
        }
        return res;
    }

    @Override
    public VehicleLicense getVehicleLicenseInfo(Long userId) {
        User u = securityUtil.getCurrUser();
        userId = UserDtoUtils.getCurrentUserId(u, userId);
        if (u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            u = userService.get(userId);
        }
        Long vehicleId = 0L;
        VehicleLicense result = null;
        if (u.getUserType().equals(CommonConstant.USER_TYPE_DRIVER)) {
            DriverUser res = driverUserService.findByUserId(userId);
            if (res != null && res.getVehicleId() != null) {
                vehicleId = res.getVehicleId();
                result = vehicleLicenseDao.getOne(vehicleId);
            }
        }

        if (result == null) {
            return new VehicleLicense();
        }
        return result;
    }

    @Override
    public void updateGpsEquipment(Long vehicldId, String gpsEquipment) {

//        vehicleposition(gpsEquipment);

        VehicleGpalInfoVo vehicleGpalInfoVo = vehicleVoMapper.getVehicleGpalInfoVo(gpsEquipment);
        if(vehicleGpalInfoVo!=null && vehicleGpalInfoVo.getVehicleId()!=null && Long.valueOf(vehicleGpalInfoVo.getVehicleId())!=vehicldId){
            throw new FreightException("设备号已绑定其他车辆");
        }
        VehicleLicense vehicleLicense = vehicleLicenseDao.getOne(vehicldId);
        vehicleLicense.setGpsEquipment(gpsEquipment);
        vehicleLicenseDao.save(vehicleLicense);

    }

    @Override
    public String vehicleRegistStatus(Long vehicldId,Integer registState,String reason) {
        User u = securityUtil.getCurrUser();
        String notificationTitle = "车辆认证";
        String msgTitle = "车辆认证";
        String msgContent = "";
        String logContent = "";
        VehicleLicense ves = vehicleLicenseDao.getOne(vehicldId);
        Long userId=ves.getManageUserId();

            if(registState==1){

                if(userId!=null){

                    Message message = new Message();
                    message.setTitle("车辆认证");
                    String content="您的提交的“车辆认证”已经通过审核啦！";
                    logContent="车辆信息审核通过";
                    message.setType("3");
                    message.setTopicId("5");
                    message.setContent(content);
                    message.setUserId(userId);
                    message=messageService.save(message);

                    MessageSend messageSend=new MessageSend();
                    messageSend.setUserId(userId);
                    messageSend.setMessageId(message.getId());
                    messageSend.setType("3");
                    messageSendService.save(messageSend);
                    msgContent=content;
                }

            }else {
                if(userId!=null){
                    //审核未通过，发送消息通知原因
                    Message message = new Message();
                    message.setTitle("车辆认证");
                    String content="您的提交的“车辆认证”审核未通过，原因："+reason+"。";
                    logContent="车辆信息审核不通过,原因："+reason;
                    message.setType("3");
                    message.setTopicId("5");
                    message.setContent(content);
                    message.setUserId(userId);
                    message=messageService.save(message);

                    MessageSend messageSend=new MessageSend();
                    messageSend.setUserId(userId);
                    messageSend.setMessageId(message.getId());
                    messageSend.setType("3");
                    messageSendService.save(messageSend);
                    msgContent=content;
                }
            }
            ves.setRegistStatus(registState);
            vehicleLicenseDao.save(ves);
            User user=userService.get(ves.getManageUserId());
            MyJPushClient jPushUtil = new MyJPushClient();
            List<String> aliasList = Arrays.asList(user.getUsername());
            jPushUtil.sendToAliasList( aliasList,notificationTitle, msgTitle, msgContent, "2",ves.getVehicleNum(),registState,null,null);

            //操作记录
            operationLogService.saveOperationLog(4,logContent,vehicldId.toString());

            return "修改成功";

    }

    @Override
    public void cancellationVehicle(Long vehicleId,Integer registStatus) {
        VehicleLicense vehicleLicense = vehicleLicenseDao.getOne(vehicleId);
        if(vehicleLicense!=null){
            vehicleLicense.setDelFlag(registStatus);
            vehicleLicenseDao.save(vehicleLicense);
        }
    }


    @Override
    public Page<VehicleDetailInfoVo> vehicleManagementList(Page<VehicleDetailInfoVo> page, VehicleDetailInfoDto vehicleDetailInfoDto){
        return vehicleVoMapper.vehicleManagementList(page , vehicleDetailInfoDto);
    }

    @Override
    public Page<VehicleDetailInfoVo> companyVehicleManagementList(Page<VehicleDetailInfoVo> page, VehicleDetailInfoDto vehicleDetailInfoDto){
        User u = securityUtil.getCurrUser();
        return vehicleVoMapper.companyVehicleManagementList(page , vehicleDetailInfoDto, u.getId());
    }



    @Override
    public List<VehicleInfoVo> getVehicleInfoByUserIds(Long[] vehicleIds){
        return vehicleVoMapper.getVehicleInfoByUserIds(vehicleIds);
    }

    @Override
    public VehicleInfoVo getVehicleInfoByUserId(Long vehicleId){
        return vehicleVoMapper.getVehicleInfoByUserId(vehicleId);
    }
}